{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#处理缺失值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实践中数值计算不可或缺，好在有很多方法可用，这个主题将介绍其中一些。不过，这些方法未必能解决你的问题。\n",
    "\n",
    "scikit-learn有一些常见的计算方法，它可以对现有数据进行变换填补`NA`值。但是，如果数据集中的缺失值是有意而为之的——例如，服务器响应时间超过100ms——那么更合适的方法是用其他包解决，像处理贝叶斯问题的PyMC，处理风险模型的lifelines，或者自己设计一套方法。\n",
    "\n",
    "<!-- TEASER_END -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##Getting ready"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "处理缺失值的第一步是创建缺失值。Numpy可以很方便的实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sklearn import datasets\n",
    "import numpy as np\n",
    "iris = datasets.load_iris()\n",
    "iris_X = iris.data\n",
    "masking_array = np.random.binomial(1, .25, iris_X.shape).astype(bool)\n",
    "iris_X[masking_array] = np.nan"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "让我们看看这几行代码，Numpy和平时用法不太一样，这里是在数组中用了一个数组作为索引。为了创建了随机的缺失值，先创建一个随机布尔值数组，其形状和`iris_X`数据集的维度相同。然后，根据布尔值数组分配缺失值。因为每次运行都是随机数据，所以`masking_array`每次都会不同。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[False,  True, False, False],\n",
       "       [False,  True, False, False],\n",
       "       [False, False, False, False],\n",
       "       [ True, False, False,  True],\n",
       "       [False, False,  True, False]], dtype=bool)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "masking_array[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 5.1,  nan,  1.4,  0.2],\n",
       "       [ 4.9,  nan,  1.4,  0.2],\n",
       "       [ 4.7,  3.2,  1.3,  0.2],\n",
       "       [ nan,  3.1,  1.5,  nan],\n",
       "       [ 5. ,  3.6,  nan,  0.2]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris_X[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##How to do it..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本书贯穿始终的一条原则（由于scikit-learn的存在）就是那些拟合与转换数据集的类都是可用的，可以在其他数据集中继续使用。具体演示如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 5.1       ,  3.05221239,  1.4       ,  0.2       ],\n",
       "       [ 4.9       ,  3.05221239,  1.4       ,  0.2       ],\n",
       "       [ 4.7       ,  3.2       ,  1.3       ,  0.2       ],\n",
       "       [ 5.86306306,  3.1       ,  1.5       ,  1.21388889],\n",
       "       [ 5.        ,  3.6       ,  3.82685185,  0.2       ]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn import preprocessing\n",
    "impute = preprocessing.Imputer()\n",
    "iris_X_prime = impute.fit_transform(iris_X)\n",
    "iris_X_prime[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意`[3,0]`位置的不同："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.8630630630630645"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris_X_prime[3,0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "nan"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris_X[3,0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##How it works..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的计算可以通过不同的方法实现。默认是均值`mean`，一共是三种：\n",
    "\n",
    "- 均值`mean`（默认方法）\n",
    "- 中位数`median`\n",
    "- 众数`most_frequent`\n",
    "\n",
    "scikit-learn会用指定的方法计算数据集中的每个缺失值，然后把它们填充好。\n",
    "\n",
    "例如，用`median`方法重新计算`iris_X`，重新初始化`impute`即可："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 5.1 ,  3.  ,  1.4 ,  0.2 ],\n",
       "       [ 4.9 ,  3.  ,  1.4 ,  0.2 ],\n",
       "       [ 4.7 ,  3.2 ,  1.3 ,  0.2 ],\n",
       "       [ 5.8 ,  3.1 ,  1.5 ,  1.3 ],\n",
       "       [ 5.  ,  3.6 ,  4.45,  0.2 ]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "impute = preprocessing.Imputer(strategy='median')\n",
    "iris_X_prime = impute.fit_transform(iris_X)\n",
    "iris_X_prime[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果数据有缺失值，后面计算过程中可能会出问题。例如，在*How to do it...*一节里面，`np.nan`作为默认缺失值，但是缺失值有很多表现形式。有时用`-1`表示。为了处理这些缺失值，可以在方法中指定那些值是缺失值。方法默认缺失值表现形式是`Nan`，就是`np.nan`的值。\n",
    "\n",
    "假设我们将`iris_X`的缺失值都用`-1`表示。看着很奇怪，但是`iris`数据集的度量值不可能是负数，因此用`-1`表示缺失值完全合理："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 5.1, -1. ,  1.4,  0.2],\n",
       "       [ 4.9, -1. ,  1.4,  0.2],\n",
       "       [ 4.7,  3.2,  1.3,  0.2],\n",
       "       [-1. ,  3.1,  1.5, -1. ],\n",
       "       [ 5. ,  3.6, -1. ,  0.2]])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris_X[np.isnan(iris_X)] = -1\n",
    "iris_X[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "填充这些缺失值也很简单："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 5.1       ,  3.05221239,  1.4       ,  0.2       ],\n",
       "       [ 4.9       ,  3.05221239,  1.4       ,  0.2       ],\n",
       "       [ 4.7       ,  3.2       ,  1.3       ,  0.2       ],\n",
       "       [ 5.86306306,  3.1       ,  1.5       ,  1.21388889],\n",
       "       [ 5.        ,  3.6       ,  3.82685185,  0.2       ]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "impute = preprocessing.Imputer(missing_values=-1)\n",
    "iris_X_prime = impute.fit_transform(iris_X)\n",
    "iris_X_prime[:5]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##There's more..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "pandas库也可以处理缺失值，而且更加灵活，但是重用性较弱："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    5.100000\n",
       "1    4.900000\n",
       "2    4.700000\n",
       "3    5.863063\n",
       "4    5.000000\n",
       "Name: sepal length (cm), dtype: float64"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "iris_X[masking_array] = np.nan\n",
    "iris_df = pd.DataFrame(iris_X, columns=iris.feature_names)\n",
    "iris_df.fillna(iris_df.mean())['sepal length (cm)'].head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "其灵活性在于，`fillna`可以填充任意统计参数值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    5.1\n",
       "1    4.9\n",
       "2    4.7\n",
       "3    7.9\n",
       "4    5.0\n",
       "Name: sepal length (cm), dtype: float64"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris_df.fillna(iris_df.max())['sepal length (cm)'].head(5)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
